package com.ecarx.camera.ui;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Space;
import android.widget.TextView;

import androidx.annotation.CallSuper;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialog;
import androidx.appcompat.app.AppCompatDialogFragment;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;

import com.ecarx.camera.R;
import com.ecarx.camera.utils.ScreenUtils;
import com.ecarx.camera.utils.Utils;

public abstract class BaseDialog extends AppCompatDialogFragment {

    protected final String TAG = getClass().getSimpleName();

    public ConstraintLayout layoutRoot;
    private ConstraintLayout layoutContent;
    private TextView tvTitle;
    private View viewTitleUnderline;
    private Button btnNegative;
    private Button btnPositive;
    private Space spaceBetweenBtnBottoms;

    private CharSequence title;
    private CharSequence negativeTxt;
    private CharSequence positiveTxt;
    private int mContentLayTopMargin;
    private OnClickListener onNegativeBtnClickListener;
    private OnClickListener onPositiveBtnClickListener;
    private boolean canceled = false;
    private boolean canceledOnTouchOutside = false;
    private OnConfigurationChangeListener onConfigurationChangeListener;
    private OnDismissListener mOnDismissListener;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Dialog dialog = new AppCompatDialog(getContext(), R.style.DialogTheme);
        dialog.getWindow().setDimAmount(0f);
        if (!canceled) {
            dialog.setOnKeyListener((dialog1, keyCode, event) -> keyCode == KeyEvent.KEYCODE_BACK);
        }
        return dialog;
    }

    /**
     * 初始化数据
     */
    @CallSuper
    protected void initData() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(getLayoutResId(), null);
    }

    /**
     * 获取 ContentView 的布局资源id
     *
     * @return ContentView 的布局资源 id
     */
    @LayoutRes
    protected abstract int getLayoutResId();

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        layoutRoot = (ConstraintLayout) view;
        bindViews();
        initViews();
    }

    /**
     * 绑定控件
     */
    @CallSuper
    protected void bindViews() {
        layoutContent = layoutRoot.findViewById(R.id.layout_content);
        if (layoutContent != null && onNegativeBtnClickListener == null && onPositiveBtnClickListener == null) {
            ViewGroup.LayoutParams params = layoutContent.getLayoutParams();
            if (params instanceof ViewGroup.MarginLayoutParams) {
                ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) params;
                marginLayoutParams.topMargin = mContentLayTopMargin;
            }
        }

        tvTitle = layoutRoot.findViewById(R.id.tv_title);
        viewTitleUnderline = layoutRoot.findViewById(R.id.view_title_underline);
        btnNegative = layoutRoot.findViewById(R.id.btn_negative);
        btnPositive = layoutRoot.findViewById(R.id.btn_positive);
        spaceBetweenBtnBottoms = layoutRoot.findViewById(R.id.space_between_btn_bottoms);

        if (canceled && canceledOnTouchOutside) {
            layoutRoot.setOnClickListener(v -> dismiss());
        }
        if (!TextUtils.isEmpty(title)) {
            tvTitle.setVisibility(View.VISIBLE);
            tvTitle.setText(title);
            viewTitleUnderline.setVisibility(View.VISIBLE);
        }
        if (!TextUtils.isEmpty(negativeTxt) && onNegativeBtnClickListener != null) {
            btnNegative.setVisibility(View.VISIBLE);
            btnNegative.setText(negativeTxt);
            btnNegative.setOnClickListener(v -> onNegativeBtnClickListener.onClick(BaseDialog.this));
        }
        if (!TextUtils.isEmpty(positiveTxt) && onPositiveBtnClickListener != null) {
            btnPositive.setVisibility(View.VISIBLE);
            btnPositive.setText(positiveTxt);
            btnPositive.setOnClickListener(v -> onPositiveBtnClickListener.onClick(BaseDialog.this));
        }
        if (btnNegative.getVisibility() == View.VISIBLE && btnPositive.getVisibility() == View.VISIBLE) {
            spaceBetweenBtnBottoms.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化控件
     */
    @CallSuper
    protected void initViews() {
        if (onConfigurationChangeListener != null) {
            onConfigurationChangeListener.onConfigurationChanged(this);
        }
        layoutRoot.setBackgroundColor(ContextCompat.getColor(Utils.getApp(), R.color.camera_base_dialog_layout_root_bg_color));
        layoutContent.setBackgroundColor(ContextCompat.getColor(Utils.getApp(), R.color.camera_base_dialog_layout_content_bg_color));
        tvTitle.setTextColor(ContextCompat.getColor(Utils.getApp(), R.color.camera_base_day_night_fg_color));
        viewTitleUnderline.setBackgroundColor(ContextCompat.getColor(Utils.getApp(), R.color.camera_base_day_night_fg_color));
        btnNegative.setBackgroundColor(ContextCompat.getColor(Utils.getApp(), R.color.camera_base_dialog_btn_negative_bg_color));
        btnNegative.setTextColor(ContextCompat.getColor(Utils.getApp(), R.color.camera_base_day_night_fg_color));
        btnPositive.setTextColor(ContextCompat.getColor(Utils.getApp(), R.color.camera_base_day_night_fg_color));
    }

    @Override
    public void onResume() {
        super.onResume();
        ViewGroup.LayoutParams layoutParams = layoutRoot.getLayoutParams();
        layoutParams.width = ScreenUtils.getAppScreenWidth();
        layoutParams.height = ScreenUtils.getAppScreenHeight();
        layoutRoot.setLayoutParams(layoutParams);
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);
        if (mOnDismissListener != null) {
            mOnDismissListener.onDismiss(this);
        }
    }

    public BaseDialog setTitle(@NonNull CharSequence title) {
        this.title = title;
        return this;
    }

    /**
     * 设置对话框内容布局的顶部边距
     * @param topMargin
     * @return
     */
    public BaseDialog setContentLayTopMargin(int topMargin) {
        this.mContentLayTopMargin = topMargin;
        return this;
    }

    public BaseDialog setNegativeBtn(@Nullable CharSequence negativeTxt, @Nullable OnClickListener onNegativeBtnClickListener) {
        this.negativeTxt = negativeTxt;
        this.onNegativeBtnClickListener = onNegativeBtnClickListener;
        return this;
    }

    public BaseDialog setPositiveBtn(@Nullable CharSequence positiveTxt, @Nullable OnClickListener onPositiveBtnClickListener) {
        this.positiveTxt = positiveTxt;
        this.onPositiveBtnClickListener = onPositiveBtnClickListener;
        return this;
    }

    public BaseDialog setCanceled(boolean canceled) {
        this.canceled = canceled;
        return this;
    }

    public BaseDialog setCanceledOnTouchOutside(boolean canceledOnTouchOutside) {
        this.canceledOnTouchOutside = canceledOnTouchOutside;
        return this;
    }

    public BaseDialog setOnConfigurationChangeListener(@NonNull OnConfigurationChangeListener onConfigurationChangeListener) {
        this.onConfigurationChangeListener = onConfigurationChangeListener;
        return this;
    }

    /**
     * 设置对话框隐藏的回调监听
     * @param onDismissListener
     * @return
     */
    public BaseDialog setOnDismissListener(OnDismissListener onDismissListener) {
        this.mOnDismissListener = onDismissListener;
        return this;
    }

    public BaseDialog show(@NonNull FragmentManager fragmentManager) {
        if (!isResumed()) {
            showNow(fragmentManager, null);
        }
        return this;
    }

    @Override
    public void dismiss() {
        super.dismissAllowingStateLoss();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        initViews();
    }

    public interface OnClickListener {
        void onClick(BaseDialog dialog);
    }

    public interface OnConfigurationChangeListener {
        void onConfigurationChanged(BaseDialog dialog);
    }

    /**
     * 对话框隐藏的回调监听
     */
    public interface OnDismissListener {
        /**
         * 对话框隐藏的回调
         * @param dialog
         */
        void onDismiss(BaseDialog dialog);
    }
}
